use serde::Serialize;
use serde_repr::Serialize_repr;

/// 状态码
#[derive(Serialize_repr, Debug, Copy, Clone)]
#[repr(i32)]
pub enum Code {
    // OK
    Ok = 0,
    // 命令未找到
    CommandNotFound = 100001,
    // 参数错误
    ParameterError = 100002,
    // 配置错误
    // ConfigError = 100003,
    // 配置不存在
    ConfigNotExists = 100004,
    // 网络错误
    NetworkError = 100005,
    // 文件系统错误
    IoError = 100006,
    // 未定义错误
    UndefinedError = 999999,
}

/// 响应结构
#[derive(Serialize, Debug)]
pub struct MagicBoxResponse<T> {
    pub code: Code,
    pub message: String,
    pub data: Option<T>,
}

impl<T> MagicBoxResponse<T> {
    /// 创建成功消息
    pub fn new_success(data: T) -> MagicBoxResponse<T> {
        MagicBoxResponse { code: Code::Ok, message: String::from("OK"), data: Some(data) }
    }

    /// 创建异常消息
    pub fn new_error(code: Code, message: String) -> MagicBoxResponse<()> {
        MagicBoxResponse { code, message, data: None }
    }

    /// 创建空消息
    pub fn new_empty_success() -> MagicBoxResponse<T> {
        MagicBoxResponse { code: Code::Ok, message: "OK".to_string(), data: None }
    }

    pub fn as_ref(&self) -> &MagicBoxResponse<T> {
        &self
    }
}
